<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="header-left">
          <text class="header-title">商品分类</text>
        </view>
        <view class="header-right">
          <view class="cart-btn" @tap="goToCart">
            <text class="cart-icon">🛒</text>
            <view v-if="cartCount > 0" class="cart-badge">{{ cartCount }}</view>
          </view>
        </view>
      </view>
    </view>

    <view class="main-content">
      <!-- 左侧分类列表 -->
      <view class="category-sidebar">
        <scroll-view class="category-scroll" scroll-y="true">
          <view 
            v-for="category in categories" 
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategoryId === category.id }"
            @tap="selectCategory(category)"
          >
            <text class="category-name">{{ category.name }}</text>
          </view>
        </scroll-view>
      </view>

      <!-- 右侧商品列表 -->
      <view class="products-content">
        <view class="products-header">
          <text class="products-title">{{ selectedCategoryName }} ({{ productList.length }}件商品)</text>
        </view>

        <scroll-view class="products-scroll" scroll-y="true">
          <view class="products-grid">
            <view 
              v-for="product in productList" 
              :key="product.id"
              class="product-card"
              @tap="goToProduct(product.id)"
            >
              <view class="product-image-container">
                <image class="product-image" :src="BASE_URL + product.imgs" mode="aspectFill"></image>
              </view>

              <view class="product-info">
                <text class="product-name">{{ product.name }}</text>
                <view class="product-price">
                  <text class="current-price">¥{{ product.price }}</text>
                </view>
                <view class="add-cart-btn" @tap.stop="addToCartHandler(product)">
                  <text class="btn-text">加入购物车</text>
                </view>
              </view>
            </view>
          </view>

          <view v-if="productList.length === 0" class="empty-state">
            <text class="empty-icon">📦</text>
            <text class="empty-text">该分类暂无商品</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>

// 这里模拟调用一个统一的加入购物车接口函数，你可以把它抽离成单独文件import
function addToCartApi(product, callback) {
  const userInfo = uni.getStorageSync('userInfo')
  console.log('用户信息:', userInfo)
  if (!userInfo || !userInfo.id) {
    uni.showToast({ title: '请先登录', icon: 'none' })
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' })
    }, 1000)
    return
  }
  const BASE_URL = getApp().$vm.$global.baseURL
  const cartItem = {
    userId: userInfo.id,
    goodId: product.id,
    count: 1,
    standard: product.standard || '默认规格' // 如果有规格可以传入
  }
  console.log('准备发送购物车请求，参数:', cartItem)
  uni.request({
    url: `${BASE_URL}/api/cart`,
    method: 'POST',
    data: cartItem,
    header: {
      'Content-Type': 'application/json',
      'Authorization': userInfo.token || ''
    },
    success: (res) => {
      console.log('加入购物车接口返回:', res)
      if (res.data && res.data.code === '200') {
        uni.showToast({ title: '已加入购物车', icon: 'success', duration: 1500 })
        callback && callback()
      } else {
        uni.showToast({ title: res.data?.msg || '加入购物车失败', icon: 'none' })
      }
    },
    fail: (err) => {
      console.error('加入购物车请求失败:', err)
      uni.showToast({ title: '网络错误，加入失败', icon: 'none' })
    }
  })
}


export default {
  data() {
    return {
      BASE_URL: getApp().$vm.$global.baseURL,
      cartCount: 0,
      categories: [],
      selectedCategoryId: null,
      selectedCategoryName: '',
      productList: []
    }
  },

  onLoad() {
    this.fetchCategories()
  },

  methods: {
    // 获取分类列表
    fetchCategories() {
      uni.request({
        url: `${this.BASE_URL}/api/category`,
        method: 'GET',
        success: (res) => {
          if (res.data && res.data.code === '200') {
            this.categories = res.data.data
            if (this.categories.length > 0) {
              const first = this.categories[0]
              this.selectCategory(first)
            }
          }
        },
        fail: () => {
          uni.showToast({ title: '加载分类失败', icon: 'none' })
        }
      })
    },

    // 获取商品数据
    fetchProducts(categoryId) {
      uni.request({
        url: `${this.BASE_URL}/api/good/page`,
        method: 'GET',
        data: {
          pageNum: 1,
          pageSize: 10,
          categoryId: categoryId
        },
        success: (res) => {
          console.log("获取分类商品数据==========", res.data.data.records)
          if (res.data && res.data.code === '200') {
            this.productList = res.data.data.records || []
          } else {
            this.productList = []
          }
        },
        fail: () => {
          uni.showToast({ title: '加载商品失败', icon: 'none' })
        }
      })
    },

    // 选择分类
    selectCategory(category) {
      this.selectedCategoryId = category.id
      this.selectedCategoryName = category.name
      this.fetchProducts(category.id)
    },

    // 加入购物车，调用统一接口
    addToCartHandler(product) {
      addToCartApi(product, () => {
        this.cartCount++
      })
    },

    goToCart() {
      uni.switchTab({ url: '/pages/cart/cart' })
    },

    goToProduct(productId) {
      uni.navigateTo({ url: `/pages/product/product?id=${productId}` })
    }
  }
}
</script>


<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航 */
.header {
  background-color: white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 50;
}

.header-content {
  max-width: 750rpx;
  margin: 0 auto;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.cart-btn {
  position: relative;
}

.cart-icon {
  font-size: 32rpx;
}

.cart-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #ff4757;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 32rpx;
  text-align: center;
}

/* 主要内容 */
.main-content {
  display: flex;
  height: calc(100vh - 120rpx);
}

/* 左侧分类 */
.category-sidebar {
  width: 200rpx;
  background-color: white;
  border-right: 1rpx solid #e0e0e0;
}

.category-scroll {
  height: 100%;
}

.category-item {
  padding: 30rpx 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.category-item.active {
  background-color: #f0f8f0;
  border-right: 4rpx solid #388f4a;
  color: #388f4a;
}

.category-icon {
  display: block;
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.category-name {
  display: block;
  font-size: 24rpx;
  font-weight: 500;
  margin-bottom: 4rpx;
}

.category-count {
  font-size: 20rpx;
  color: #999;
}

/* 右侧商品 */
.products-content {
  flex: 1;
  padding: 30rpx;
}

.products-header {
  margin-bottom: 30rpx;
}

.products-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.products-scroll {
  height: calc(100vh - 240rpx);
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
}

.product-card {
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.product-image-container {
  position: relative;
}

.product-image {
  width: 100%;
  height: 280rpx;
}

.product-tag {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  background-color: #ff4757;
  color: white;
  font-size: 20rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.product-info {
  padding: 24rpx;
}

.product-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}

.product-rating {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.star {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.rating-text {
  font-size: 20rpx;
  color: #666;
  margin-right: 20rpx;
}

.sales-text {
  font-size: 20rpx;
  color: #999;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.current-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4757;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.add-cart-btn {
  width: 80%;
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  text-align: center;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-icon {
  display: block;
  font-size: 80rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}
</style>
